<template>
  <div class="flex h-screen bg-gray-50">
    <!-- 侧边栏 -->
    <Sidebar 
      :sidebar-open="sidebarOpen"
      :selected-robot="selectedRobot"
      :search-query="searchQuery"
      :selected-conversation="selectedConversation"
      :conversations="conversations"
      :filtered-conversations="filteredConversations"
      @toggle-sidebar="toggleSidebar"
      @new-conversation="createNewConversation"
      @select-conversation="handleConversationSelect"
      @update:selected-robot="updateSelectedRobot"
      @update:search-query="updateSearchQuery"
    />

    <!-- 主内容区域 -->
    <div class="flex-1 flex">
      <!-- 中间问答界面 -->
      <div class="flex-1 flex flex-col bg-white overflow-hidden" style="width: 40%; min-width: 0;">
        <!-- 对话区域 -->
        <div class="flex-1 overflow-y-auto p-6" ref="chatContainer">
          <div class="max-w-4xl mx-auto">
            <!-- 欢迎界面 -->
            <div v-if="messages.length === 0" class="flex items-center justify-center h-full">
              <div class="text-center py-12">
                <div class="w-16 h-16 rounded-xl bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center mx-auto mb-4">
                  <i class="fas fa-comments text-white text-2xl"></i>
                </div>
                <h3 class="text-xl font-semibold text-slate-800 mb-2">开始新的对话</h3>
                <p class="text-slate-600">请输入您的问题，我将为您提供专业的回答</p>
              </div>
            </div>

            <!-- 对话消息 -->
            <div v-else class="space-y-6">
              <div 
                v-for="message in messages" 
                :key="message.id"
                :class="['flex', message.role === 'user' ? 'justify-end' : 'justify-start']"
              >
                <!-- 用户消息 -->
                <div v-if="message.role === 'user'" class="flex items-start space-x-3 max-w-[92%]">
                  <div class="bg-gradient-to-r from-blue-500 to-indigo-600 rounded-2xl rounded-br-sm p-4 shadow-lg">
                    <p class="text-white text-sm leading-relaxed">{{ message.content }}</p>
                    <div class="timestamp user-timestamp text-blue-200 mt-2 text-xs">{{ formatTime(message.created_at) }}</div>
                  </div>
                  <div class="w-8 h-8 rounded-full bg-gradient-to-br from-blue-400 to-indigo-500 flex items-center justify-center shadow-md">
                    <span class="text-white text-sm">{{ authStore.username?.charAt(0).toUpperCase() }}</span>
                  </div>
                </div>
                
                <!-- 机器人消息 -->
                <div v-else class="flex items-start space-x-3 max-w-[92%]">
                  <div class="w-8 h-8 rounded-full bg-gradient-to-br from-purple-500 to-pink-500 flex items-center justify-center shadow-md">
                    <i class="fas fa-robot text-white text-sm"></i>
                  </div>
                  <div class="glass-effect rounded-2xl p-6 shadow-xl border border-slate-200">
                    <div class="mb-4">
                      <p class="text-slate-700 text-sm leading-relaxed mb-3">
                        我正在处理您的问题："{{ message.content }}"
                      </p>
                      <div class="timestamp text-xs text-slate-500">{{ formatTime(message.created_at) }}</div>
                    </div>
                    
                    <!-- 进度条 -->
                    <div class="mb-6">
                      <div class="flex justify-between text-xs text-slate-500 mb-2">
                        <span>处理进度</span>
                        <span>{{ progress }}%</span>
                      </div>
                      <div class="w-full bg-slate-200 rounded-full h-2">
                        <div class="progress-bar" :style="{ width: progress + '%' }"></div>
                      </div>
                    </div>
                    
                    <!-- Todo List -->
                    <div class="space-y-3">
                      <div 
                        v-for="task in processingTasks" 
                        :key="task.id"
                        class="todo-item processing-node p-4 rounded-xl border-2 bg-white cursor-pointer transition-all duration-200"
                        :class="getTaskClasses(task)"
                        :data-step="task.id"
                        :data-task="task.id"
                        @click="handleTaskClick(task)"
                      >
                        <div class="flex items-center justify-between">
                          <div class="flex items-center space-x-3">
                            <div class="w-6 h-6 rounded-full flex items-center justify-center" :class="getTaskIconClasses(task)">
                              <i v-if="task.status === 'processing'" class="loading-dots">
                                <span></span>
                                <span></span>
                                <span></span>
                              </i>
                              <i v-else :class="getTaskIcon(task)" class="text-white text-xs"></i>
                            </div>
                            <div>
                              <p class="font-medium text-slate-800">{{ task.title }}</p>
                              <p class="text-xs text-slate-500 mt-1">{{ task.description }}</p>
                            </div>
                          </div>
                          <span class="text-xs font-medium" :class="getTaskStatusClasses(task)">
                            {{ getTaskStatus(task) }}
                          </span>
                        </div>
                        <div class="task-details" :class="{ 'show': task.showDetails }">
                          <h4>{{ getTaskDetailTitle(task) }}</h4>
                          <ul>
                            <li v-for="(item, index) in getTaskDetailItems(task)" :key="index">{{ item }}</li>
                          </ul>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="border-t border-slate-200 p-4 bg-white">
          <div class="flex items-end space-x-3">
            <div class="flex-1">
              <textarea 
                v-model="inputMessage"
                @keyup.enter.ctrl="handleSendMessage"
                class="w-full p-4 border-2 border-slate-200 rounded-xl resize-none focus:outline-none focus:border-indigo-500 focus:ring-4 focus:ring-indigo-50 transition-all"
                placeholder="输入您的问题..."
                rows="1"
              ></textarea>
              <!-- 附件选项 -->
              <div class="flex items-center justify-between mt-3">
                <div class="flex items-center space-x-2">
                  <button @click="uploadImage" class="attachment-btn p-2 rounded-lg hover:bg-slate-100 transition-all" data-tooltip="上传图片" title="上传图片">
                    <i class="fas fa-image text-slate-600"></i>
                  </button>
                  <button @click="uploadFile" class="attachment-btn p-2 rounded-lg hover:bg-slate-100 transition-all" data-tooltip="上传文件" title="上传文件">
                    <i class="fas fa-file text-slate-600"></i>
                  </button>
                  <button @click="insertCodeSnippet" class="attachment-btn p-2 rounded-lg hover:bg-slate-100 transition-all" data-tooltip="代码片段" title="代码片段">
                    <i class="fas fa-code text-slate-600"></i>
                  </button>
                  <div class="w-px h-6 bg-slate-300 mx-2"></div>
                  <button @click="startVoiceInput" class="attachment-btn p-2 rounded-lg hover:bg-red-100 transition-all" :class="{ 'voice-recording': isRecording }" data-tooltip="语音输入" title="语音输入">
                    <i class="fas fa-microphone" :class="{ 'text-slate-600': !isRecording, 'text-white': isRecording }"></i>
                  </button>
                </div>
                <div class="flex items-center space-x-2">
                  <button @click="clearConversation" class="p-2 rounded-lg hover:bg-slate-100 transition-all" title="清空对话">
                    <i class="fas fa-trash text-slate-600"></i>
                  </button>
                  <span class="text-xs text-slate-400">按 Enter 发送</span>
                  <button 
                    @click="handleSendMessage"
                    :disabled="!inputMessage.trim()"
                    class="bg-gradient-to-r from-indigo-500 to-purple-600 text-white p-3 rounded-xl hover:from-indigo-600 hover:to-purple-700 transition-all duration-200 shadow-lg hover:shadow-xl disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <i class="fas fa-paper-plane"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧结果面板 -->
      <div class="bg-slate-50 border-l border-slate-200 flex flex-col overflow-hidden" style="width: 45%; min-width: 0;">
        <!-- 标题栏 -->
        <div class="bg-white border-b border-slate-200 p-6">
          <div class="flex items-center justify-between">
            <div>
              <h2 class="font-bold text-slate-800 text-lg">回答详情</h2>
              <p class="text-sm text-slate-500">展示模型处理过程和输出结果</p>
            </div>
            <div class="flex items-center space-x-2">
              <div class="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
            </div>
          </div>
        </div>

        <!-- 结果内容 -->
        <div class="flex-1 overflow-y-auto p-6 space-y-4" id="resultArea">
          <div v-if="resultPanels.length === 0" class="flex items-center justify-center h-full">
            <div class="text-center">
              <div class="w-16 h-16 rounded-xl bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center mx-auto mb-4 opacity-50">
                <i class="fas fa-chart-line text-white text-2xl"></i>
              </div>
              <h3 class="text-lg font-semibold text-slate-800 mb-2">等待处理结果</h3>
              <p class="text-slate-600">开始对话后，处理结果将在这里显示</p>
            </div>
          </div>

          <DynamicPanels 
            :panels="resultPanels"
            :conversation-type="currentConversationType"
            @panel-click="handleResultPanelClick"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, watch } from 'vue'
import { useHomeState } from '../composables/home/useHomeState'
import Sidebar from '../components/home/Sidebar.vue'
import DynamicPanels from '../components/home/DynamicPanels.vue'
import { formatTime, getTaskIcon, getTaskIconClasses, getTaskStatus, getTaskStatusClasses, getTaskClasses } from '../utils/home'
import { useAuthStore } from '../stores/auth'

// 状态管理
const {
  sidebarOpen,
  selectedRobot,
  searchQuery,
  selectedConversation,
  conversations,
  filteredConversations,
  currentConversationType,
  messages,
  processingTasks,
  resultPanels,
  progress,
  conversationStats,
  toggleSidebar,
  updateSelectedRobot,
  updateSearchQuery,
  loadConversation,
  createNewConversation,
  sendMessage,
  handlePanelClick,
  resetState
} = useHomeState()

// 本地状态
const inputMessage = ref('')
const chatContainer = ref<HTMLElement>()
const authStore = useAuthStore()
const isRecording = ref(false)

// 辅助函数
const getTaskDetailTitle = (task: any) => {
  return `${task.title} - 详细信息`
}

const getTaskDetailItems = (task: any) => {
  return [
    '处理状态: ' + task.status,
    '创建时间: ' + formatTime(task.created_at),
    '预计完成时间: ' + formatTime(task.estimated_completion)
  ]
}

const handleTaskClick = (task: any) => {
  console.log('handleTaskClick called:', task)
  
  // 移除所有任务和面板的激活状态
  processingTasks.value.forEach(t => t.active = false)
  resultPanels.value.forEach(p => p.active = false)
  
  // 激活当前任务
  task.active = true
  task.showDetails = !task.showDetails
  
  // 激活对应的结果面板
  const correspondingPanel = resultPanels.value.find(p => p.id === task.id)
  console.log('Found corresponding panel:', correspondingPanel)
  if (correspondingPanel) {
    correspondingPanel.active = true
    console.log('Activated panel:', correspondingPanel)
    // 滚动到结果面板
    scrollToResultPanel(task.id)
  }
}

const handleResultPanelClick = (panel: any) => {
  console.log('handleResultPanelClick called:', panel)
  
  // 移除所有任务和面板的激活状态
  processingTasks.value.forEach(t => t.active = false)
  resultPanels.value.forEach(p => p.active = false)
  
  // 激活当前面板
  panel.active = true
  console.log('Activated panel:', panel)
  
  // 激活对应的处理任务
  const correspondingTask = processingTasks.value.find(t => t.id === panel.id)
  console.log('Found corresponding task:', correspondingTask)
  if (correspondingTask) {
    correspondingTask.active = true
    console.log('Activated task:', correspondingTask)
    // 滚动到处理任务
    scrollToProcessingTask(panel.id)
  }
}

// 功能函数
const uploadImage = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.onchange = (e) => {
    const file = (e.target as HTMLInputElement).files?.[0]
    if (file) {
      console.log('上传图片:', file.name)
      // 可以在这里添加图片预览功能
    }
  }
  input.click()
}

const uploadFile = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.txt,.pdf,.doc,.docx,.xls,.xlsx,.csv'
  input.onchange = (e) => {
    const file = (e.target as HTMLInputElement).files?.[0]
    if (file) {
      console.log('上传文件:', file.name)
      // 可以在这里添加文件预览功能
    }
  }
  input.click()
}

const insertCodeSnippet = () => {
  // 创建一个代码输入对话框
  const code = prompt('请输入代码片段:')
  if (code) {
    console.log('插入代码片段:', code)
    // 可以在这里添加代码高亮和格式化功能
  }
}

const startVoiceInput = () => {
  if (isRecording.value) {
    // 如果正在录音，则停止录音
    stopVoiceInput()
    return
  }
  
  // 检查浏览器是否支持语音识别
  if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition
    const recognition = new SpeechRecognition()
    
    recognition.lang = 'zh-CN'
    recognition.continuous = false
    recognition.interimResults = false
    
    recognition.onstart = () => {
      isRecording.value = true
      console.log('开始语音输入...')
    }
    
    recognition.onresult = (event) => {
      const transcript = event.results[0][0].transcript
      inputMessage.value += transcript
      console.log('语音识别结果:', transcript)
    }
    
    recognition.onerror = (event) => {
      console.error('语音识别错误:', event.error)
      isRecording.value = false
    }
    
    recognition.onend = () => {
      isRecording.value = false
      console.log('语音输入结束')
    }
    
    recognition.start()
  } else {
    alert('您的浏览器不支持语音识别功能')
  }
}

const stopVoiceInput = () => {
  isRecording.value = false
  console.log('停止语音输入')
}

const clearConversation = () => {
  if (confirm('确定要清空当前对话吗？')) {
    resetState()
    console.log('对话已清空')
  }
}

const copyToClipboard = () => {
  const sqlCode = `-- 深圳市最近30天AQI数据查询
SELECT
    date,
    aqi_value,
    pm25,
    pm10,
    no2,
    so2,
    co,
    o3,
    quality_level,
    primary_pollutant
FROM air_quality_data
WHERE city = '深圳市'
    AND date >= DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY)
ORDER BY date ASC
LIMIT 1000;`
  
  navigator.clipboard.writeText(sqlCode).then(() => {
    console.log('SQL代码已复制到剪贴板')
  }).catch(err => {
    console.error('复制失败:', err)
  })
}

const downloadReport = () => {
  const reportContent = `深圳市AQI趋势分析报告

分析时间: ${new Date().toLocaleDateString()}

执行摘要:
根据最近30天深圳市AQI数据分析，空气质量整体呈现改善趋势。平均AQI值为85.2，
较上月下降15%。优良天数占比达到85%，主要污染物为PM2.5。

主要发现:
• AQI整体呈现下降趋势，空气质量逐步改善
• 优良天数占比达到85%，较上月提升5个百分点
• PM2.5仍然是主要污染物，占比45%
• 周末空气质量普遍优于工作日

建议措施:
1. 继续加强工业排放管控
2. 优化交通流量管理
3. 增加城市绿化覆盖率

预期效果:
• AQI再降低10-15%
• 优良天数达到90%
• 重污染天数减少50%

---
报告由博沃智慧AI系统生成`
  
  const blob = new Blob([reportContent], { type: 'text/plain;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `深圳AQI趋势分析报告_${new Date().toISOString().split('T')[0]}.txt`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
  
  console.log('报告下载完成')
}

const handleConversationSelect = (conversation: any) => {
  selectedConversation.value = conversation
  loadConversationWithType(conversation.type)
}

const loadConversationWithType = async (type: string) => {
  // 清空当前状态
  messages.value = []
  progress.value = 0
  processingTasks.value = []
  resultPanels.value = []
  currentConversationType.value = type
  
  // 加载对应类型的对话数据
  switch(type) {
    case 'knowledge':
      loadKnowledgeConversation()
      break
    case 'data':
      loadDataConversation()
      break
    case 'image':
      loadImageConversation()
      break
    case 'code':
      loadCodeConversation()
      break
  }
  
  // 启动处理流程
  await startProcessing(type)
}

// 对话加载函数
const loadKnowledgeConversation = () => {
  const userMessage = {
    id: 1,
    role: 'user',
    content: '深圳监测站有哪些分析方法可以分析地表水中铜？',
    created_at: new Date()
  }
  
  const assistantMessage = {
    id: 2,
    role: 'assistant',
    content: '深圳监测站有哪些分析方法可以分析地表水中铜？',
    created_at: new Date()
  }
  
  messages.value = [userMessage, assistantMessage]
  initializeProcessingTasks('knowledge')
}

const loadDataConversation = () => {
  const userMessage = {
    id: 1,
    role: 'user',
    content: '最近一个月深圳市的AQI变化趋势，请帮我分析一下',
    created_at: new Date()
  }
  
  const assistantMessage = {
    id: 2,
    role: 'assistant',
    content: '最近一个月深圳市的AQI变化趋势，请帮我分析一下',
    created_at: new Date()
  }
  
  messages.value = [userMessage, assistantMessage]
  initializeProcessingTasks('data')
}

const loadImageConversation = () => {
  const userMessage = {
    id: 1,
    role: 'user',
    content: '请分析这张臭氧变化趋势图',
    created_at: new Date()
  }
  
  const assistantMessage = {
    id: 2,
    role: 'assistant',
    content: '请分析这张臭氧变化趋势图',
    created_at: new Date()
  }
  
  messages.value = [userMessage, assistantMessage]
  initializeProcessingTasks('image')
}

const loadCodeConversation = () => {
  const userMessage = {
    id: 1,
    role: 'user',
    content: '请帮我分析这段Python代码的性能问题',
    created_at: new Date()
  }
  
  const assistantMessage = {
    id: 2,
    role: 'assistant',
    content: '请帮我分析这段Python代码的性能问题',
    created_at: new Date()
  }
  
  messages.value = [userMessage, assistantMessage]
  initializeProcessingTasks('code')
}

// 初始化处理任务
const initializeProcessingTasks = (type: string) => {
  const taskConfig = {
    knowledge: [
      {
        id: 1,
        title: '1. 问题解析',
        description: '分析用户问题意图',
        icon: 'fas fa-search',
        status: 'pending',
        showDetails: false,
        active: false,
        created_at: new Date(),
        estimated_completion: new Date(Date.now() + 30000)
      },
      {
        id: 2,
        title: '2. 知识检索',
        description: '检索内部知识库',
        icon: 'fas fa-database',
        status: 'pending',
        showDetails: false,
        active: false,
        created_at: new Date(),
        estimated_completion: new Date(Date.now() + 60000)
      },
      {
        id: 3,
        title: '3. 信息整理',
        description: '整理相关信息',
        icon: 'fas fa-file-alt',
        status: 'pending',
        showDetails: false,
        active: false,
        created_at: new Date(),
        estimated_completion: new Date(Date.now() + 90000)
      },
      {
        id: 4,
        title: '4. 答案生成',
        description: '生成专业答案',
        icon: 'fas fa-magic',
        status: 'pending',
        showDetails: false,
        active: false,
        created_at: new Date(),
        estimated_completion: new Date(Date.now() + 120000)
      },
      {
        id: 5,
        title: '5. 质量检查',
        description: '检查答案质量',
        icon: 'fas fa-check-circle',
        status: 'pending',
        showDetails: false,
        active: false,
        created_at: new Date(),
        estimated_completion: new Date(Date.now() + 150000)
      }
    ],
    data: [
      {
        id: 1,
        title: '1. 数据获取',
        description: '获取AQI监测数据',
        icon: 'fas fa-download',
        status: 'pending',
        showDetails: false,
        active: false,
        created_at: new Date(),
        estimated_completion: new Date(Date.now() + 30000)
      },
      {
        id: 2,
        title: '2. 数据清洗',
        description: '清洗和预处理数据',
        icon: 'fas fa-filter',
        status: 'pending',
        showDetails: false,
        active: false,
        created_at: new Date(),
        estimated_completion: new Date(Date.now() + 60000)
      },
      {
        id: 3,
        title: '3. 趋势分析',
        description: '分析变化趋势',
        icon: 'fas fa-chart-line',
        status: 'pending',
        showDetails: false,
        active: false,
        created_at: new Date(),
        estimated_completion: new Date(Date.now() + 90000)
      },
      {
        id: 4,
        title: '4. 可视化生成',
        description: '生成趋势图表',
        icon: 'fas fa-chart-bar',
        status: 'pending',
        showDetails: false,
        active: false,
        created_at: new Date(),
        estimated_completion: new Date(Date.now() + 120000)
      },
      {
        id: 5,
        title: '5. 报告生成',
        description: '生成分析报告',
        icon: 'fas fa-file-alt',
        status: 'pending',
        showDetails: false,
        active: false,
        created_at: new Date(),
        estimated_completion: new Date(Date.now() + 150000)
      }
    ],
    image: [
      {
        id: 1,
        title: '1. 图像上传',
        description: '上传待分析图像',
        icon: 'fas fa-upload',
        status: 'pending',
        showDetails: false,
        active: false,
        created_at: new Date(),
        estimated_completion: new Date(Date.now() + 30000)
      },
      {
        id: 2,
        title: '2. 图像预处理',
        description: '预处理图像数据',
        icon: 'fas fa-crop',
        status: 'pending',
        showDetails: false,
        active: false,
        created_at: new Date(),
        estimated_completion: new Date(Date.now() + 60000)
      },
      {
        id: 3,
        title: '3. 特征提取',
        description: '提取图像特征',
        icon: 'fas fa-fingerprint',
        status: 'pending',
        showDetails: false,
        active: false,
        created_at: new Date(),
        estimated_completion: new Date(Date.now() + 90000)
      },
      {
        id: 4,
        title: '4. 模式识别',
        description: '识别图像模式',
        icon: 'fas fa-eye',
        status: 'pending',
        showDetails: false,
        active: false,
        created_at: new Date(),
        estimated_completion: new Date(Date.now() + 120000)
      },
      {
        id: 5,
        title: '5. 结果生成',
        description: '生成分析结果',
        icon: 'fas fa-file-image',
        status: 'pending',
        showDetails: false,
        active: false,
        created_at: new Date(),
        estimated_completion: new Date(Date.now() + 150000)
      }
    ],
    code: [
      {
        id: 1,
        title: '1. 代码解析',
        description: '解析代码结构',
        icon: 'fas fa-code',
        status: 'pending',
        showDetails: false,
        active: false,
        created_at: new Date(),
        estimated_completion: new Date(Date.now() + 30000)
      },
      {
        id: 2,
        title: '2. 性能分析',
        description: '分析性能问题',
        icon: 'fas fa-tachometer-alt',
        status: 'pending',
        showDetails: false,
        active: false,
        created_at: new Date(),
        estimated_completion: new Date(Date.now() + 60000)
      },
      {
        id: 3,
        title: '3. 问题识别',
        description: '识别潜在问题',
        icon: 'fas fa-bug',
        status: 'pending',
        showDetails: false,
        active: false,
        created_at: new Date(),
        estimated_completion: new Date(Date.now() + 90000)
      },
      {
        id: 4,
        title: '4. 优化建议',
        description: '提供优化建议',
        icon: 'fas fa-lightbulb',
        status: 'pending',
        showDetails: false,
        active: false,
        created_at: new Date(),
        estimated_completion: new Date(Date.now() + 120000)
      },
      {
        id: 5,
        title: '5. 重构建议',
        description: '生成重构建议',
        icon: 'fas fa-tools',
        status: 'pending',
        showDetails: false,
        active: false,
        created_at: new Date(),
        estimated_completion: new Date(Date.now() + 150000)
      }
    ]
  }
  
  processingTasks.value = taskConfig[type] || []
}

// 启动处理流程
const startProcessing = async (type: string) => {
  const steps = [
    { step: 1, progress: 20, status: 'completed' },
    { step: 2, progress: 40, status: 'completed' },
    { step: 3, progress: 60, status: 'completed' },
    { step: 4, progress: 80, status: 'completed' },
    { step: 5, progress: 100, status: 'completed' }
  ]
  
  for (const stepData of steps) {
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    // 更新任务状态
    const task = processingTasks.value.find(t => t.id === stepData.step)
    if (task) {
      task.status = stepData.status as 'pending' | 'processing' | 'completed'
      // 如果任务完成，触发滚动到对应结果面板
      if (task.status === 'completed') {
        onTaskCompleted(task.id)
      }
    }
    
    // 更新进度
    progress.value = stepData.progress
    
    // 添加结果面板
    addResultPanel(stepData.step, type)
    
    // 滚动到最新内容
    scrollToLatestContent()
  }
}

// 添加结果面板
const addResultPanel = (step: number, type: string) => {
  const panel = {
    id: step,
    title: getPanelTitle(step, type),
    content: getPanelContent(step, type),
    icon: getPanelIcon(step),
    iconBg: getPanelIconBg(step),
    step: `步骤 ${step}`,
    stepBadge: getPanelStepBadge(step),
    timestamp: new Date(),
    active: true,
    visible: true,
    conversationType: type,
    extraInfo: getPanelExtraInfo(step, type),
    extraInfoClass: getPanelExtraInfoClass(step, type)
  }
  
  resultPanels.value.push(panel)
}

// 任务完成回调
const onTaskCompleted = (taskId: number) => {
  const panel = resultPanels.value.find(p => p.id === taskId)
  if (panel) {
    scrollToResultPanel(taskId)
  }
}

// 滚动到结果面板
const scrollToResultPanel = (taskId: number) => {
  setTimeout(() => {
    const element = document.querySelector(`[data-result="${taskId}"]`)
    if (element) {
      element.scrollIntoView({ behavior: 'smooth', block: 'center' })
    }
  }, 100)
}

// 滚动到处理任务
const scrollToProcessingTask = (taskId: number) => {
  setTimeout(() => {
    const element = document.querySelector(`[data-step="${taskId}"]`)
    if (element) {
      element.scrollIntoView({ behavior: 'smooth', block: 'center' })
    }
  }, 100)
}

// 滚动到最新内容
const scrollToLatestContent = () => {
  setTimeout(() => {
    const chatArea = document.getElementById('chatArea')
    if (chatArea) {
      chatArea.scrollTop = chatArea.scrollHeight
    }
  }, 100)
}

// 获取面板标题
const getPanelTitle = (step: number, type: string) => {
  const titles: Record<string, string[]> = {
    knowledge: [
      '问题解析完成',
      '知识检索完成',
      '信息整理完成',
      '答案生成完成',
      '质量检查完成'
    ],
    data: [
      '数据获取完成',
      '数据清洗完成',
      '趋势分析完成',
      '可视化生成完成',
      '报告生成完成'
    ],
    image: [
      '图像上传完成',
      '图像预处理完成',
      '特征提取完成',
      '模式识别完成',
      '结果生成完成'
    ],
    code: [
      '代码解析完成',
      '性能分析完成',
      '问题识别完成',
      '优化建议完成',
      '重构建议完成'
    ]
  }
  
  return titles[type]?.[step - 1] || `步骤 ${step} 完成`
}

// 获取面板内容
const getPanelContent = (step: number, type: string) => {
  return `这是 ${getPanelTitle(step, type)} 的详细内容...`
}

// 获取面板图标
const getPanelIcon = (step: number) => {
  const icons = [
    'fas fa-check-circle',
    'fas fa-chart-line',
    'fas fa-database',
    'fas fa-file-alt',
    'fas fa-trophy'
  ]
  return icons[step - 1] || 'fas fa-check'
}

// 获取面板图标背景
const getPanelIconBg = (step: number) => {
  const colors = [
    'bg-green-500',
    'bg-blue-500',
    'bg-purple-500',
    'bg-orange-500',
    'bg-red-500'
  ]
  return colors[step - 1] || 'bg-gray-500'
}

// 获取面板步骤徽章
const getPanelStepBadge = (step: number) => {
  const badges = [
    '进行中',
    '处理中',
    '分析中',
    '生成中',
    '已完成'
  ]
  return badges[step - 1] || '处理中'
}

// 获取面板额外信息
const getPanelExtraInfo = (step: number, type: string) => {
  return `处理时间: ${step * 1.5}s`
}

// 获取面板额外信息样式
const getPanelExtraInfoClass = (step: number, type: string) => {
  return 'text-green-600'
}

// 对话类型配置
const conversationTypes = [
  {
    id: 'knowledge',
    title: '知识问答',
    description: '专业知识查询与解答',
    icon: 'fas fa-book-open',
    iconBg: 'bg-blue-500'
  },
  {
    id: 'data',
    title: '数据分析',
    description: '数据查询与趋势分析',
    icon: 'fas fa-chart-line',
    iconBg: 'bg-indigo-500'
  },
  {
    id: 'image',
    title: '图像识别',
    description: '图像处理与特征提取',
    icon: 'fas fa-image',
    iconBg: 'bg-green-500'
  },
  {
    id: 'code',
    title: '代码分析',
    description: '代码质量与性能优化',
    icon: 'fas fa-code',
    iconBg: 'bg-purple-500'
  }
]

// 发送消息
const handleSendMessage = async () => {
  if (!inputMessage.value.trim()) return
  
  await sendMessage(inputMessage.value)
  inputMessage.value = ''
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight
  }
}

// 监听消息变化
watch(() => Array.isArray(messages) ? messages.length : 0, scrollToBottom)

onMounted(() => {
  // 初始化
})
</script>

<style scoped>
/* 进度条样式 */
.progress-bar {
  height: 3px;
  background: linear-gradient(90deg, #667eea, #764ba2);
  border-radius: 2px;
  transition: width 0.5s ease-in-out;
}

/* 处理步骤动画 */
.todo-item {
  animation: todoFadeIn 0.6s cubic-bezier(0.34, 1.56, 0.64, 1);
}

@keyframes todoFadeIn {
  from {
    opacity: 0;
    transform: translateX(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

/* 处理节点基础样式 */
.processing-node {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

/* 已完成任务样式 */
.processing-node.completed-task {
  border-left: 3px solid #10b981 !important;
}

.processing-node.completed-task:hover {
  transform: translateX(4px);
  box-shadow: 0 4px 12px rgba(16, 185, 129, 0.2);
}

/* 处理中任务样式 */
.processing-node.active {
  border-left: 3px solid #3b82f6 !important;
}

/* 时间戳样式 */
.timestamp {
  font-size: 0.75rem;
  opacity: 0.7;
}

/* 玻璃态效果 */
.glass-effect {
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(12px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

/* 加载动画 */
.loading-dots {
  display: flex;
  gap: 2px;
}

.loading-dots span {
  width: 4px;
  height: 4px;
  background: currentColor;
  border-radius: 50%;
  animation: loading 1.4s infinite ease-in-out both;
}

.loading-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes loading {
  0%, 80%, 100% {
    transform: scale(0);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 语音录制动画 */
.voice-recording {
  background: #ef4444;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

/* 任务详情样式 */
.task-details {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.3s ease;
  margin-top: 0;
}

.task-details.show {
  max-height: 200px;
  margin-top: 1rem;
}

.task-details h4 {
  font-size: 0.875rem;
  font-weight: 600;
  margin-bottom: 0.5rem;
  color: #374151;
}

.task-details ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.task-details li {
  font-size: 0.75rem;
  color: #6b7280;
  padding: 0.25rem 0;
  border-bottom: 1px solid #f3f4f6;
}

.task-details li:last-child {
  border-bottom: none;
}

/* 处理节点样式 */
.processing-node {
  transition: all 0.3s ease;
  border-color: #e5e7eb;
}

.processing-node:hover {
  border-color: #6366f1;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

.processing-node.active {
  border-color: #10b981;
  box-shadow: 0 4px 12px rgba(16, 185, 129, 0.2);
  background-color: rgba(16, 185, 129, 0.05);
}

/* 结果面板样式 */
.result-panel {
  transition: all 0.3s ease;
}

.result-panel.active {
  border-color: #6366f1;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
}

/* 自定义滚动条 */
.custom-scrollbar::-webkit-scrollbar {
  width: 6px;
}

.custom-scrollbar::-webkit-scrollbar-track {
  background: #f1f5f9;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}

.custom-scrollbar::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}
</style>